<!-- 出库明细 -->
<template>
  <div class="outbound-detail-container">
    <!-- 筛选区域 -->
    <div class="controls-section">
      <div class="filters">
        <div class="filter-item">
          <label>关键词</label>
          <el-input v-model="queryParams.keyword" placeholder="请输入出库流水号/出库单号/产品名称" clearable />
        </div>
        <div class="filter-item">
          <label>产品分类</label>
          <el-select v-model="queryParams.category" placeholder="请选择产品分类" clearable>
            <el-option
              v-for="item in productCategories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>
      <div class="actions">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>
    </div>

    <!-- 表格区域（与入库明细统一的原生表格样式） -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected"></th>
            <th>出库流水号</th>
            <th>出库时间</th>
            <th>出库类型</th>
            <th>出库单号</th>
            <th>产品名称</th>
            <th>规格</th>
            <th>分类</th>
            <th>单位</th>
            <th>仓库</th>
            <th>出库数量</th>
            <th>操作人</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="13" style="text-align: center; padding: 20px;">加载中...</td>
          </tr>
          <tr v-for="(item, index) in detailList" :key="index">
            <td><input type="checkbox" v-model="item.selected"></td>
            <td class="link-style">{{ item.outboundSerialNumber || '-' }}</td>
            <td>{{ parseTime(item.outboundTime, '{y}-{m}-{d} {h}:{i}') }}</td>
            <td>{{ formatOutboundType(item.outboundType) }}</td>
            <td class="link-style">{{ item.outboundNo || '-' }}</td>
            <td>{{ item.productName || '-' }}</td>
            <td>{{ item.productSpec || '-' }}</td>
            <td>{{ formatCategory(item.category) }}</td>
            <td>{{ item.unit || '-' }}</td>
            <td>{{ item.warehouseName || '-' }}</td>
            <td>{{ item.outboundQuantity || '-' }}</td>
            <td>{{ item.operator || '-' }}</td>
            <td>{{ item.remark || '-' }}</td>
          </tr>
        </tbody>
      </table>

      <!-- 底部分页与操作区域 -->
      <div class="footer-section">
        <div class="footer-left">
          <input type="checkbox" v-model="allSelected">
          <label>全选</label>
          <button class="btn-secondary" @click="handleExport">导出</button>
        </div>
        <div class="pagination">
          <button @click="onPageChange(queryParams.pageNum - 1)" :disabled="queryParams.pageNum === 1">&lt;</button>
          <button v-for="page in totalPages" :key="page" @click="onPageChange(page)" :class="{ active: queryParams.pageNum === page }">{{ page }}</button>
          <button @click="onPageChange(queryParams.pageNum + 1)" :disabled="queryParams.pageNum === totalPages">&gt;</button>
          <select v-model.number="queryParams.pageSize" @change="onPageSizeChange">
            <option :value="5">5条/页</option>
            <option :value="10">10条/页</option>
            <option :value="20">20条/页</option>
            <option :value="50">50条/页</option>
          </select>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { pageOutboundDetails, exportOutboundDetails } from '@/api/warehouse/OutboundDetail'
import { ElMessage } from 'element-plus'

export default {
  name: 'OutboundDetail',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 出库明细表格数据
      detailList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        outboundSerialNumber: undefined,
        outboundNo: undefined,
        productName: undefined,
        category: undefined,
        outboundType: undefined,
        warehouseName: undefined
      },
      // 产品分类字典
      productCategories: [
        { value: 1, label: '原材料' },
        { value: 2, label: '半成品' },
        { value: 3, label: '成品' },
      ],
    }
  },
  computed: {
    allSelected: {
      get() {
        return this.detailList.length > 0 && this.detailList.every(item => item.selected)
      },
      set(val) {
        this.detailList.forEach(item => item.selected = val)
      }
    },
    totalPages() {
      return Math.max(1, Math.ceil(this.total / this.queryParams.pageSize))
    }
  },
  created() {
    console.log('=== 出库明细页面诊断 ===')
    console.log('组件名称:', this.$options.name)
    console.log('当前路由:', this.$route.path)
    console.log('OutboundDetail组件已创建，开始获取数据...')
    console.log('初始查询参数:', this.queryParams)
    this.getList()
  },
  methods: {
    /** 查询出库明细列表 */
    async getList() {
      this.loading = true
      try {
        // 基础分页与筛选
        const baseParams = {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize,
          category: this.queryParams.category,
          outboundType: this.queryParams.outboundType
        }

        // 智能关键词尝试顺序：CKLL* → 流水号；CK* → 单号；纯字母数字 → 依次尝试 流水号/单号/产品名；其他 → 产品名
        const kw = (this.queryParams.keyword || '').toString().trim()
        const attempts = []
        if (kw) {
          if (/^CKLL/i.test(kw)) {
            attempts.push({ outboundSerialNumber: kw })
          } else if (/^CK/i.test(kw)) {
            attempts.push({ outboundNo: kw })
          } else if (/^[0-9A-Za-z-]+$/.test(kw)) {
            attempts.push({ outboundSerialNumber: kw })
            attempts.push({ outboundNo: kw })
            attempts.push({ productName: kw })
          } else {
            attempts.push({ productName: kw })
          }
        } else {
          attempts.push({})
        }

        let finalData = null
        for (const extra of attempts) {
          const dtoParams = { ...baseParams, ...extra }
          const resp = await pageOutboundDetails(dtoParams)
          const payload = resp?.data || {}
          const ok = payload.success === true || payload.code === 200 || payload.code === 0
          if (!ok) continue
          const data = payload.data || {}
          const records = data.records || data.list || []
          if (records.length > 0 || !kw) {
            finalData = { records, total: data.total || records.length || 0 }
            break
          }
        }

        if (!finalData) {
          this.detailList = []
          this.total = 0
        } else {
          this.detailList = finalData.records
          this.total = finalData.total
        }
      } catch (error) {
        console.error('获取出库明细失败:', error)
        ElMessage.error('获取出库明细失败')
        this.detailList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    // 分页（与入库明细统一）
    onPageChange(page) {
      const next = Math.min(Math.max(1, page), this.totalPages)
      if (next === this.queryParams.pageNum) return
      this.queryParams.pageNum = next
      this.getList()
    },
    onPageSizeChange() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 搜索按钮操作 */
    handleSearch() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: this.queryParams.pageSize,
        keyword: undefined,
        category: undefined,
        outboundType: undefined
      }
      this.handleSearch()
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有出库明细数据项?').then(() => {
        this.exportLoading = true
        // 导出时不需要分页参数
        const exportParams = { ...this.queryParams }
        delete exportParams.pageNum
        delete exportParams.pageSize

        return exportOutboundDetails(exportParams)
      }).catch(() => {
        // 用户取消导出
        return Promise.reject()
      }).finally(() => {
        this.exportLoading = false
      })
    },
    // 格式化出库类型
    formatOutboundType(type) {
      const typeMap = {
        0: '销售出库',
        1: '生产领料',
        2: '委外发料',
        3: '采购退货',
        4: '其他出库'
      }
      return typeMap[type] || '未知类型'
    },
    // 获取出库类型标签
    getOutboundTypeTag(type) {
      const typeMap = {
        0: 'success',
        1: 'primary',
        2: 'warning',
        3: 'danger',
        4: 'info'
      }
      return typeMap[type] || ''
    },
    // 格式化分类
    formatCategory(category) {
      const categoryMap = {
        1: '原材料',
        2: '半成品',
        3: '成品',
        4: '耗材',
        5: '工具',
        6: '设备',
        7: '配件',
        8: '包装',
        9: '其他'
      }
      return categoryMap[category] || '未知分类'
    },
    // 时间格式化方法
    parseTime(time, pattern) {
      if (!time) return '-'
      const date = new Date(time)
      if (isNaN(date.getTime())) return time

      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')

      return pattern
        .replace('{y}', year)
        .replace('{m}', month)
        .replace('{d}', day)
        .replace('{h}', hours)
        .replace('{i}', minutes)
    }
  }
}
</script>

<style scoped>
.outbound-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.controls-section {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.filters {
    display: flex;
    gap: 24px;
    align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  white-space: nowrap;
}

.filter-item input, .filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.filter-item input {
    width: 240px;
}

.actions {
  margin-left: auto;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff !important;
  color: #606266 !important;
  border: 1px solid #dcdfe6 !important;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  box-shadow: none !important;
}

.btn-secondary:hover,
.btn-secondary:active,
.btn-secondary:focus {
  background-color: #fff !important;
  color: #606266 !important;
  box-shadow: none !important;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
}

.link-style {
    color: #409eff;
    cursor: pointer;
}

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style>
